<template>
  <div class="content_body">
    <div class="pageTitle">
      角色管理
    </div>
    <div class="page_body">
      <div class="tool">
        <el-row :gutter="24">
          <el-col
            :xs="16"
            :sm="12"
            :md="8"
            :lg="6"
            :xl="4"
            min-width="100px"
            max-width="200px"
          >
            <el-input
              placeholder="请输入内容"
              size="small"
              v-model="keyWord"
              class="input-with-select"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                v-on:click="search()"
              >
              </el-button>
            </el-input>
          </el-col>
          <el-col :xs="16" :sm="12" :md="8" :lg="6" :xl="4">
            <el-button
              size="small"
              icon="el-icon-search"
              v-on:click="addRole()"
              class="my_btn"
              >新增</el-button
            >
            <el-button
              size="small"
              icon="el-icon-refresh"
              class="my_btn"
              v-on:click="refresh()"
            ></el-button>
          </el-col>
        </el-row>
      </div>
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="order" label="序号" min-width="20%">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名" min-width="40%">
        </el-table-column>
        <el-table-column label="操作" min-width="40%">
          <template slot-scope="scope">
            <el-button
              v-show="false"
              @click.native.prevent="changeRole(scope.$index, tableData)"
              type="primary"
              icon="el-icon-edit"
              title="修改"
              circle
              size="small"
            >
            </el-button>
            <el-button
              @click.native.prevent="deleteRole(scope.$index, tableData)"
              type="danger"
              icon="el-icon-delete"
              circle
              title="删除"
              size="small"
            >
            </el-button>
            <el-button type="info" @click.native.prevent="setRolePermission(scope.$index, tableData)" title="配置" icon="el-icon-setting" size="small" circle></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog :title="isAddRole?'添加用户':'修改用户'" :visible.sync="dialogFormVisible" width="30%" max-width="500px" min-width="300px">
      <el-form :model="dialogRoleForm" :rules="rules" ref="dialogRoleForm">
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="角色名"
              :label-width="formLabelWidth"
              prop="roleName"
            >
              <el-input
                size="small"
                v-model="dialogRoleForm.roleName"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          class="my_btn"
          size="small"
          @click="dialogFormVisible = false"
          >取 消</el-button
        >
        <el-button
          class="my_btn"
          size="small"
          type="primary"
          @click="submitRoleForm('dialogRoleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { queryRole, deleteRole ,addRole,changeRole} from "@/api/api";
export default {
  name: "user",
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      total: 0,
      keyWord: "",
      loading: false,
      tableData: [],
      dialogFormVisible: false,
      formLabelWidth: "80px",
      isAddRole:false,
      dialogRoleForm: {
        roleId:"",
        roleName: ""
      },
      rules: {
        userName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" }
        ]
      }
    };
  },
  mounted: function() {
    this.getData();
  },
  methods: {
    //请求数据
     async getData() {
      this.loading = true;
      const parmas = {
        keyWord: this.keyWord,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      };
      let data = await queryRole(parmas);
      this.tableData = data.data.list.map((item, index) => {
        //计算数据序号，并添加到数组中
        item.order = (this.pageNum - 1) * this.pageSize + index + 1;
        return item;
      });
      this.total = data.data.total;
      this.loading = false;
    },
    //添加用户按钮触发事件
    addRole() {
      this.clearDialogRoleForm()
      this.dialogFormVisible = true;
      this.isAddRole=true;
    },
    //修改按钮触发事件
    changeRole(index, rows){
      this.clearDialogRoleForm()
      this.dialogFormVisible = true;
      this.isAddRole=false;
      this.dialogRoleForm.roleId=rows[index].roleId
      this.dialogRoleForm.roleName=rows[index].roleName
    },
    //清空弹窗内容方法
    clearDialogRoleForm(){
      this.dialogRoleForm.roleId=''
      this.dialogRoleForm.roleName=''
    },
    //配置角色权限
    setRolePermission(index, rows){
      this.$router.push({
        path:"/permission",
        query:{
          roleId:rows[index].roleId,
          roleName:rows[index].roleName
      }})
    },
    //表格显示条数变化触发函数
    handleSizeChange(val) {
      this.pageSize = val;
      this.getData();
    },
    //当前页数变化触发函数
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getData();
    },
    //删除按钮，打开删除提示框
    deleteRole(index, rows) {
      this.$confirm(
        "此操作将永久删除:" + rows[index].roleName + ", 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(async () => {
          const params = {
            roleId: rows[index].roleId
          };
          await deleteRole(params);
          this.getData();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //搜索按钮触发事件
    search() {
      this.getData();
    },
    //重置表格
    refresh() {
      (this.pageNum = 1),
        (this.pageSize = 10),
        (this.keyWord = ""),
        this.getData();
    },
    //弹窗关闭按钮事件
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => {});
    },
    submitRoleForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          //判断是否是新增用户
           if(this.isAddRole){
             let params={
               ...this.dialogRoleForm,
               loading:true
             }
             //如果userId不存在，则删除parsms中的userId属性
             if(params.roleId==''){
               delete params.roleId
             }
              await addRole(params)
              this.getData()
              this.dialogFormVisible=false
           }else{
              let params={
               ...this.dialogRoleForm,
               loading:true
             }
              await changeRole(params)
              this.getData()
              this.dialogFormVisible=false
           }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.content_body {
  position: relative;
  box-sizing: border-box;
  background: white;
  .pageTitle {
    font-size: 20px;
    font-weight: bold;
    padding: 10px 20px 10px 20px;
    box-shadow: 0px 1px 0px 0px rgba($color: #000000, $alpha: 0.05);
  }
  .page_body {
    padding: 20px;
    .tool {
      margin-bottom: 20px;
    }
    .pagination {
      margin-top: 30px;
    }
  }
}
</style>
<style lang="scss">
@import "@/css/xz.base.scss"
</style>
